<?php
namespace app\admin\service;

use app\model\Product as ProductModel;
use app\model\ProductSpecs;
class Product
{
    public function getPageData($page,$size,$where)
    {
        return ProductModel::with('specs')->where($where)->order('id','desc')->paginate($size,false,[
            'page'=>$page
        ]);
    }
    public  function readByID(int $id)
    {
        return ProductModel::where('id',$id)->find();
    }
    public function deleteByID($id)
    {
        return  ProductModel::destroy($id);
    }
    public function hasEmpty($id)
    {
        $result=ProductModel::findOrEmpty($id)->isEmpty();
        return  $result;
    }
    /**
     * 添加商品
     * 包括一般信息和规格信息，规则字段$data['specs']
     */
    public function edit($data)
    {
        $model=new ProductModel();
        $model->startTrans();
        try {
                if(isset($data['id'])) $model=$model->where('id',$data['id'])->find();
                $prodcutSaveRes=$model->save($data);
                if(!$prodcutSaveRes) throw new \Exception('商品保存失败');
                $product_id=$model->id;
                $stock=0;
                if(isset($data['id']))
                {
                    $prduct_del_res=(new ProductSpecs())->where(['product_id'=>$product_id])->delete();
                    if(!$prduct_del_res) throw new \Exception('删除商品规格失败');
                }
                $specs_arr=$data['specs'];
                foreach($specs_arr as $specs)
                {
                    $stock+=$specs['stock'];
                    $specs['product_id']=$product_id;
                    $prodSpecsSave=(new ProductSpecs)->save($specs);
                    if(!$prodSpecsSave) throw new \Exception('商品规格保存出错');
                }
                $prodStockSave=$model->where('id',$product_id)->save(['stock'=>$stock]);
                if(!$prodStockSave) throw new \Exception('商品库存保存出错');
                $model->commit();
                return true;
        } catch (\Exception $e) {
            $model->rollback();
            throw new \Exception($e->getMessage());
            return false;
        }
    }
}
